package com.yxcz.serviceImpl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;
import javax.persistence.EntityNotFoundException;

import org.springframework.stereotype.Service;

import com.yxcz.dao.RoleDAO;
import com.yxcz.dao.UserDAO;
import com.yxcz.exception.PasswordNotCorrectException;
import com.yxcz.model.AddRoleForm;
import com.yxcz.model.Role;
import com.yxcz.model.UpdateRoleForm;
import com.yxcz.model.User;
import com.yxcz.service.RoleService;

@Service
public class RoleServiceImpl implements RoleService {
	
	@Resource
	RoleDAO roleDAO;
	@Resource
	UserDAO userDAO;

	@SuppressWarnings("unchecked")
	@Override
	public ArrayList<Role> list() {
		// TODO Auto-generated method stub
		
		return (ArrayList<Role>) roleDAO.query("from Role role order by sequence asc",new HashMap<String,Object>());
	}

	@Override
	public Role getRole(int id) {
		// TODO Auto-generated method stub
		return roleDAO.find(id);
	}

	@Override
	public void deleteById(Integer id) {
		// TODO Auto-generated method stub
		Role role = new Role();
		role.setId(id);
		roleDAO.delete(role);
	}

	@Override
	public void update(UpdateRoleForm form) {
		// TODO Auto-generated method stub
		Role role = roleDAO.find(form.getId());
		role.setName(form.getName());
		role.setSequence(form.getSequence());
		role.setRemark(form.getRemark());
		role.setStatus(form.isStatus());
		roleDAO.save(role);
	}

	@Override
	public void add(AddRoleForm form) throws Exception {
		// TODO Auto-generated method stub
		Role role = new Role();
		role.setName(form.getName());
		role.setSequence(form.getSequence());
		role.setStatus(form.isStatus());
		role.setRemark(form.getRemark());
		roleDAO.add(role);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Set<Role> getRolesByUserId(Integer id) {
		// TODO Auto-generated method stub
		
		return (Set<Role>) userDAO.find(id).getRoles();
	}

	@Override
	public boolean setRole(int uid,Integer[] rid) {
		// TODO Auto-generated method stub
		User user = userDAO.find(uid);
		if(user==null)
			return false;
	
		Set<Role> roles = new HashSet<>();
		for (int i : rid) {
			Role role = new Role();
			role.setId(i);
			roles.add(role);
		}
		user.setRoles(roles);
		userDAO.save(user);
		return true;
		
		
	}
	
	

	

}
